using System;
using System.Collections.Generic;
using System.Text;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using System.Workflow.ComponentModel;
using System.Collections;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WorkflowActions;

using Nintex.Workflow;
using Nintex.Workflow.Activities.Adapters;
using NintexCustomWFActivities;
using NintexCustomWFActions;
using Microsoft.SharePoint.Administration;
using System.Security;
using System.Collections.Specialized;
using System.Web;
using System.Management.Automation.Runspaces;
using System.Net;

namespace NintexCustomWFActions
{
    public class ExecutePowerShellAdapter : GenericRenderingAction, IRunNow
    {
        private const string ScriptProperty = "Script";
        private const string SignatureProperty = "Signature";
        private const string Var1Property = "Var1";
        private const string Var2Property = "Var2";
        private const string Var3Property = "Var3";
        private const string Var4Property = "Var4";
        private const string Var5Property = "Var5";
        private const string SecureProperty = "Secure";
        private const string Var1OutputProperty = "Var1Output";
        private const string Var2OutputProperty = "Var2Output";
        private const string Var3OutputProperty = "Var3Output";
        private const string Var4OutputProperty = "Var4Output";
        private const string Var5OutputProperty = "Var5Output";
        private const string SecureStoreAppIdProperty = "SecureStoreAppId";
        private const string ListItemIdProperty = "ListItemId";

        string LoggingAreaCategory = LoggingConstants.LOGGING_AREA + "/" + LoggingConstants.LOGGING_AREA_CATEGORY_ACTION;

        public Nintex.Workflow.RunNowResult ExecuteRunNow(RunNowContext context)
        {
            try
            {
                //Logger.LogTraceMessage(LoggingConstants.TraceMessage.Begin, LoggingAreaCategory);

                Dictionary<string, ActivityParameterHelper> parameters = context.ParameterHelpers;
                string executionResult = "OK";
                bool isSiteWorkflow = true;
                SPList workflowList = null;
                SPListItem workflowItem = null;
                NameValueCollection qscoll = HttpUtility.ParseQueryString(System.Web.HttpContext.Current.Request.UrlReferrer.Query);
                string category = qscoll["Category"];
                if (category == null)
                {
                    string errorMsg = "Error finding workflow category, URL=" + System.Web.HttpContext.Current.Request.UrlReferrer.Query;
                    //Logger.LogToOperations(errorMsg, (int)EventId.ActivityError, EventSeverity.Error, LoggingAreaCategory);
                    return new RunNowResult() { Data = errorMsg };
                }
                //check to see if site workflow or list workflow
                isSiteWorkflow = category.Equals("Site", StringComparison.InvariantCultureIgnoreCase);
                if (!isSiteWorkflow)
                {
                    Guid listGuid = new Guid(qscoll["ListId"]);
                    workflowList = SPContext.Current.Web.Lists[listGuid];

                    if (parameters[ListItemIdProperty].Value.Length > 0)
                    {
                        workflowItem = workflowList.GetItemById(int.Parse(parameters[ListItemIdProperty].Value));
                        //Logger.LogToDeveloper(string.Format("ListUrl={0}, ListItemId={1}", workflowList.RootFolder.Url, workflowItem.ID), (int)EventId.TraceMessage, TraceSeverity.Verbose, LoggingAreaCategory);
                    }

                }
                string res = ExecutePowerShellRunAs(parameters, isSiteWorkflow, workflowList, workflowItem);
                executionResult = res + "\r\nOK";

                //Logger.LogTraceMessage(LoggingConstants.TraceMessage.End, LoggingAreaCategory);
                return new RunNowResult() { Data = executionResult };
            }
            catch (System.SystemException ex)
            {
                //Logger.LogToOperations(ex, (int)EventId.ActivityError, EventSeverity.Error, LoggingAreaCategory);
                throw;
            }
        }

        private string ExecutePowerShellRunAs(Dictionary<string, ActivityParameterHelper> parameters, bool IsSiteWorkflow, SPList WorkflowList, SPListItem WorkflowItem)
        {
            StringBuilder sb = new StringBuilder();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                WorkflowList.ParentWeb.AllowUnsafeUpdates = true;
                if (IsSigningRequired)
                {
                    //Logger.LogToDeveloper("Signing is required", (int)EventId.TraceMessage, TraceSeverity.Verbose, LoggingAreaCategory);
                    ValidateSignature(parameters[ScriptProperty].Value, parameters[SignatureProperty].Value);
                }

                using (Runspace runspace = RunspaceFactory.CreateRunspace())
                {
                    runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
                    runspace.Open();

                    //runspace.SessionStateProxy.SetVariable("ctx", __Context);
                    //runspace.SessionStateProxy.SetVariable("sharePointService", (ISharePointService)executionContext.GetService(typeof(ISharePointService)));
                    //runspace.SessionStateProxy.SetVariable("listItemService", (IListItemService)executionContext.GetService(typeof(IListItemService)));

                    runspace.SessionStateProxy.SetVariable("site", SPContext.Current.Site);
                    runspace.SessionStateProxy.SetVariable("web", SPContext.Current.Web);

                    //Logger.LogToDeveloper(string.Format("Site URL={0}, Web Url={1}", SPContext.Current.Site.Url, SPContext.Current.Web.Url), (int)EventId.TraceMessage, TraceSeverity.Verbose, LoggingAreaCategory);

                    if (!IsSiteWorkflow)
                    {
                        runspace.SessionStateProxy.SetVariable("list", WorkflowList);
                        runspace.SessionStateProxy.SetVariable("item", WorkflowItem);
                        //Logger.LogToDeveloper(string.Format("List URL={0}", WorkflowList.RootFolder.Url), (int)EventId.TraceMessage, TraceSeverity.Verbose, LoggingAreaCategory);
                        //if(WorkflowItem!=null)
                            //Logger.LogToDeveloper(string.Format("Item ID={1}", WorkflowList.RootFolder.Url, WorkflowItem.ID), (int)EventId.TraceMessage, TraceSeverity.Verbose, LoggingAreaCategory);
                        //else
                            //Logger.LogToDeveloper("Item ID was not provided", (int)EventId.TraceMessage, TraceSeverity.Verbose, LoggingAreaCategory);
                    }

                    //Logger.LogToDeveloper(string.Format("Input parameters Var1={0}, Var2={1}, Var3={2}, Var4={3}, Var5={4}", parameters[Var1Property].Value, parameters[Var2Property].Value, parameters[Var3Property].Value, parameters[Var4Property].Value, parameters[Var5Property].Value), (int)EventId.TraceMessage, TraceSeverity.Verbose, LoggingAreaCategory);

                    runspace.SessionStateProxy.SetVariable("var1", parameters[Var1Property].Value);
                    runspace.SessionStateProxy.SetVariable("var2", parameters[Var2Property].Value);
                    runspace.SessionStateProxy.SetVariable("var3", parameters[Var3Property].Value);
                    runspace.SessionStateProxy.SetVariable("var4", parameters[Var4Property].Value);
                    runspace.SessionStateProxy.SetVariable("var5", parameters[Var5Property].Value);

                    if (!String.IsNullOrEmpty(parameters[SecureProperty].Value))
                    {
                        //Logger.LogToDeveloper("Secure:" + parameters[SecureProperty].Value, (int)EventId.TraceMessage, TraceSeverity.Verbose, LoggingAreaCategory);
                        runspace.SessionStateProxy.SetVariable("secure", DecryptString(parameters[SecureProperty].Value));
                    }

                    if (!String.IsNullOrEmpty(parameters[SecureStoreAppIdProperty].Value))
                    {
                        //Logger.LogToDeveloper(string.Format("Using SecureStoreAppId SecureStoreAppId={0}", parameters[SecureStoreAppIdProperty].Value), (int)EventId.TraceMessage, TraceSeverity.Verbose, LoggingAreaCategory);
                        NetworkCredential cred = NintexCustomWFActivities.Helper.GetSecureStoreCredentials(SPContext.Current.Site, parameters[SecureStoreAppIdProperty].Value);
                        runspace.SessionStateProxy.SetVariable("credential", cred);
                    }

                    Pipeline pipeline = runspace.CreatePipeline();

                    //need to figure out how this is done in runnow mode
                    //string resolvedScript = NintexCustomWFActivities.Helper.ReplaceTokens(ctx.AddContextDataToString(this.Script), __Context);
                    //pipeline.Commands.AddScript(resolvedScript);

                    pipeline.Commands.AddScript(parameters[ScriptProperty].Value);

                    pipeline.Invoke();

                    string fmt = "$var{0}={1}\r\n";
                    string logToDev = "Output parameters";
                    for (int i = 1; i <= 5; i++)
                    {
                        string res = runspace.SessionStateProxy.GetVariable("var" + i.ToString()) as String;
                        sb.AppendFormat(fmt, i, res);
                        logToDev += string.Format(" Param{0}={1},", i, res);
                    }
                    //Logger.LogToDeveloper(logToDev, (int)EventId.TraceMessage, TraceSeverity.Verbose, LoggingAreaCategory);

                    runspace.Close();
                }
                WorkflowList.ParentWeb.AllowUnsafeUpdates = false;

            });
            return sb.ToString();
        }

        private static string DecryptString(string encryptedString)
        {
            string str = encryptedString;

            if (encryptedString.StartsWith(Constants.EncryptedPasswordPrefix))
            {
                str = NintexCustomWFActivities.Helper.DecryptString(str.Replace(Constants.EncryptedPasswordPrefix, String.Empty));
            }
            return str;
        }

        private bool IsSiteWorkflow()
        {

            throw new NotImplementedException();
        }

        public bool AdministratorControlled
        {
            get
            {
                return false;
            }
        }


        public override NWActionConfig GetDefaultConfig(GetDefaultConfigContext context)
        {
            // Build the default parameters for the action. Populate an array of ActivityParameters to represent each parameter. 
            try
            {
                //Logger.LogTraceMessage(LoggingConstants.TraceMessage.Begin, LoggingAreaCategory);
                NWActionConfig config = new NWActionConfig(this);

                config.Parameters = new ActivityParameter[15];

                config.Parameters[0] = new ActivityParameter();
                config.Parameters[0].Name = ScriptProperty;
                config.Parameters[0].PrimitiveValue = new PrimitiveValue();
                config.Parameters[0].PrimitiveValue.Value = GetDefaultScript();
                config.Parameters[0].PrimitiveValue.ValueType = SPFieldType.Text.ToString();
                config.Parameters[0].RunNowOptions = new RunNowParameterOptions() { Required = true, ControlType = RunNowControlType.MultiLine };

                config.Parameters[1] = new ActivityParameter();
                config.Parameters[1].Name = SignatureProperty;
                config.Parameters[1].PrimitiveValue = new PrimitiveValue();
                config.Parameters[1].PrimitiveValue.Value = string.Empty;
                config.Parameters[1].PrimitiveValue.ValueType = SPFieldType.Text.ToString();
                config.Parameters[1].RunNowOptions = new RunNowParameterOptions() { Required = IsSigningRequired, GroupWithPrevious = true, ControlType = RunNowControlType.MultiLine };

                config.Parameters[2] = new ActivityParameter();
                config.Parameters[2].Name = Var1Property;
                config.Parameters[2].PrimitiveValue = new PrimitiveValue();
                config.Parameters[2].PrimitiveValue.Value = string.Empty;
                config.Parameters[2].PrimitiveValue.ValueType = SPFieldType.Text.ToString();
                config.Parameters[2].RunNowOptions = new RunNowParameterOptions();

                config.Parameters[3] = new ActivityParameter();
                config.Parameters[3].Name = Var2Property;
                config.Parameters[3].PrimitiveValue = new PrimitiveValue();
                config.Parameters[3].PrimitiveValue.Value = string.Empty;
                config.Parameters[3].PrimitiveValue.ValueType = SPFieldType.Text.ToString();
                config.Parameters[3].RunNowOptions = new RunNowParameterOptions() { GroupWithPrevious = true };

                config.Parameters[4] = new ActivityParameter();
                config.Parameters[4].Name = Var3Property;
                config.Parameters[4].PrimitiveValue = new PrimitiveValue();
                config.Parameters[4].PrimitiveValue.Value = string.Empty;
                config.Parameters[4].PrimitiveValue.ValueType = SPFieldType.Text.ToString();
                config.Parameters[4].RunNowOptions = new RunNowParameterOptions() { GroupWithPrevious = true };

                config.Parameters[5] = new ActivityParameter();
                config.Parameters[5].Name = Var4Property;
                config.Parameters[5].PrimitiveValue = new PrimitiveValue();
                config.Parameters[5].PrimitiveValue.Value = string.Empty;
                config.Parameters[5].PrimitiveValue.ValueType = SPFieldType.Text.ToString();
                config.Parameters[5].RunNowOptions = new RunNowParameterOptions() { GroupWithPrevious = true };

                config.Parameters[6] = new ActivityParameter();
                config.Parameters[6].Name = Var5Property;
                config.Parameters[6].PrimitiveValue = new PrimitiveValue();
                config.Parameters[6].PrimitiveValue.Value = string.Empty;
                config.Parameters[6].PrimitiveValue.ValueType = SPFieldType.Text.ToString();
                config.Parameters[6].RunNowOptions = new RunNowParameterOptions() { GroupWithPrevious = true };

                config.Parameters[7] = new ActivityParameter();
                config.Parameters[7].Name = SecureProperty;
                config.Parameters[7].PrimitiveValue = new PrimitiveValue();
                config.Parameters[7].PrimitiveValue.Value = string.Empty;
                config.Parameters[7].PrimitiveValue.ValueType = SPFieldType.Text.ToString();
                config.Parameters[7].RunNowOptions = new RunNowParameterOptions();

                config.Parameters[8] = new ActivityParameter();
                config.Parameters[8].Name = SecureStoreAppIdProperty;
                config.Parameters[8].PrimitiveValue = new PrimitiveValue();
                config.Parameters[8].PrimitiveValue.Value = string.Empty;
                config.Parameters[8].PrimitiveValue.ValueType = SPFieldType.Text.ToString();
                config.Parameters[8].RunNowOptions = new RunNowParameterOptions();

                config.Parameters[9] = new ActivityParameter();
                config.Parameters[9].Name = Var1OutputProperty;
                config.Parameters[9].Variable = new NWWorkflowVariable();

                config.Parameters[10] = new ActivityParameter();
                config.Parameters[10].Name = Var2OutputProperty;
                config.Parameters[10].Variable = new NWWorkflowVariable();

                config.Parameters[11] = new ActivityParameter();
                config.Parameters[11].Name = Var3OutputProperty;
                config.Parameters[11].Variable = new NWWorkflowVariable();

                config.Parameters[12] = new ActivityParameter();
                config.Parameters[12].Name = Var4OutputProperty;
                config.Parameters[12].Variable = new NWWorkflowVariable();

                config.Parameters[13] = new ActivityParameter();
                config.Parameters[13].Name = Var5OutputProperty;
                config.Parameters[13].Variable = new NWWorkflowVariable();

                config.Parameters[14] = new ActivityParameter();
                config.Parameters[14].Name = ListItemIdProperty;
                config.Parameters[14].PrimitiveValue = new PrimitiveValue();
                config.Parameters[14].PrimitiveValue.Value = string.Empty;
                config.Parameters[14].PrimitiveValue.ValueType = SPFieldType.Text.ToString();
                config.Parameters[14].RunNowOptions = new RunNowParameterOptions();

                // Set the default label for the action.
                config.TLabel = ActivityReferenceCollection.FindByAdapter(this).Name;
                //Logger.LogTraceMessage(LoggingConstants.TraceMessage.End, LoggingAreaCategory);

                return config;
            }
            catch (System.SystemException ex)
            {
                //Logger.LogToOperations(ex, (int)EventId.ActionError, EventSeverity.Error, LoggingAreaCategory);
                throw;
            }
        }

        private string GetDefaultScript()
        {
            try
            {
                //Logger.LogTraceMessage(LoggingConstants.TraceMessage.Begin, LoggingAreaCategory);
                string defScript = "";
                if (SPFarm.Local.Properties.ContainsKey(Constants.ExecutePowerShellActivityDefaultScript))
                    defScript = (string)SPFarm.Local.Properties[Constants.ExecutePowerShellActivityDefaultScript];
                //Logger.LogTraceMessage(LoggingConstants.TraceMessage.End, LoggingAreaCategory);
                return defScript;
            }
            catch (System.SystemException ex)
            {
                //Logger.LogToOperations(ex, (int)EventId.ActionError, EventSeverity.Error, LoggingAreaCategory);
                throw;
            }
        }

        private bool ValidateSignature(string script, string signature)
        {
            try
            {
                //Logger.LogTraceMessage(LoggingConstants.TraceMessage.Begin, LoggingAreaCategory);
                if (String.IsNullOrEmpty(signature))
                    return false;
                bool isValid = NintexCustomWFActivities.Helper.VerifySignature(script, signature);
                //Logger.LogTraceMessage(LoggingConstants.TraceMessage.End, LoggingAreaCategory);
                return isValid;
            }
            catch (System.SystemException ex)
            {
                //Logger.LogToOperations(ex, (int)EventId.ActionError, EventSeverity.Error, LoggingAreaCategory);
                throw;
            }
        }

        public override bool ValidateConfig(ActivityContext context)
        {
            try
            {
                //Logger.LogTraceMessage(LoggingConstants.TraceMessage.Begin, LoggingAreaCategory);
                // Add logic to validate the configuration here.

                bool isValid = true;

                Dictionary<string, ActivityParameterHelper> parameters = context.Configuration.GetParameterHelpers();

                if (!parameters[ScriptProperty].Validate(typeof(string), context))
                {
                    isValid &= false;
                    validationSummary.AddError(ScriptProperty, ValidationSummaryErrorType.CannotBeBlank);
                }

                if (IsSigningRequired)
                {
                    //Logger.LogToDeveloper("Signing is required", (int)EventId.TraceMessage, TraceSeverity.Verbose, LoggingAreaCategory);
                    bool isValidSignature = ValidateSignature(parameters[ScriptProperty].Value, parameters[SignatureProperty].Value);
                    if (!isValidSignature)
                    {
                        isValid &= false;
                        validationSummary.AddError("The script signature is not valid.");
                    }
                }

                //Logger.LogTraceMessage(LoggingConstants.TraceMessage.End, LoggingAreaCategory);

                return isValid;
            }
            catch (System.SystemException ex)
            {
                //Logger.LogToOperations(ex, (int)EventId.ActionError, EventSeverity.Error, LoggingAreaCategory);
                throw;
            }
        }

        public override CompositeActivity AddActivityToWorkflow(PublishContext context)
        {
            // Create an instance of the Activity and set its properties based on config. Add it to the parent activity.
            try
            {
                //Logger.LogTraceMessage(LoggingConstants.TraceMessage.Begin, LoggingAreaCategory);

                Dictionary<string, ActivityParameterHelper> parameters = context.Config.GetParameterHelpers();

                ExecutePowerShellActivity activity = new ExecutePowerShellActivity();
                parameters[ScriptProperty].AssignTo(activity, ExecutePowerShellActivity.ScriptProperty, context);
                parameters[SignatureProperty].AssignTo(activity, ExecutePowerShellActivity.SignatureProperty, context);
                parameters[Var1Property].AssignTo(activity, ExecutePowerShellActivity.Var1Property, context);
                parameters[Var2Property].AssignTo(activity, ExecutePowerShellActivity.Var2Property, context);
                parameters[Var3Property].AssignTo(activity, ExecutePowerShellActivity.Var3Property, context);
                parameters[Var4Property].AssignTo(activity, ExecutePowerShellActivity.Var4Property, context);
                parameters[Var5Property].AssignTo(activity, ExecutePowerShellActivity.Var5Property, context);
                parameters[SecureProperty].AssignTo(activity, ExecutePowerShellActivity.SecureProperty, context);
                parameters[SecureStoreAppIdProperty].AssignTo(activity, ExecutePowerShellActivity.SecureStoreAppIdProperty, context);

                parameters[Var1OutputProperty].AssignTo(activity, ExecutePowerShellActivity.Var1OutProperty, context);
                parameters[Var2OutputProperty].AssignTo(activity, ExecutePowerShellActivity.Var2OutProperty, context);
                parameters[Var3OutputProperty].AssignTo(activity, ExecutePowerShellActivity.Var3OutProperty, context);
                parameters[Var4OutputProperty].AssignTo(activity, ExecutePowerShellActivity.Var4OutProperty, context);
                parameters[Var5OutputProperty].AssignTo(activity, ExecutePowerShellActivity.Var5OutProperty, context);

                // Set standard context items
                activity.SetBinding(ExecutePowerShellActivity.__ContextProperty, new ActivityBind(context.ParentWorkflow.Name, StandardWorkflowDataItems.__context));
                activity.SetBinding(ExecutePowerShellActivity.__ListItemProperty, new ActivityBind(context.ParentWorkflow.Name, StandardWorkflowDataItems.__item));
                activity.SetBinding(ExecutePowerShellActivity.__ListIdProperty, new ActivityBind(context.ParentWorkflow.Name, StandardWorkflowDataItems.__list));

                ActivityFlags f = new ActivityFlags();
                f.AddLabelsFromConfig(context.Config);
                f.AssignTo(activity);

                context.ParentActivity.Activities.Add(activity);
                //Logger.LogTraceMessage(LoggingConstants.TraceMessage.End, LoggingAreaCategory);
                return null;
            }
            catch (System.SystemException ex)
            {
                //Logger.LogToOperations(ex, (int)EventId.ActionError, EventSeverity.Error, LoggingAreaCategory);
                throw;
            }

        }

        public override NWActionConfig GetConfig(RetrieveConfigContext context)
        {
            // Read the properties from context.Activity and update the values in the NWActionConfig.

            try
            {
                //Logger.LogTraceMessage(LoggingConstants.TraceMessage.Begin, LoggingAreaCategory);
                NWActionConfig config = this.GetDefaultConfig(context);

                Dictionary<string, ActivityParameterHelper> parameters = config.GetParameterHelpers();

                parameters[ScriptProperty].RetrieveValue(context.Activity, ExecutePowerShellActivity.ScriptProperty, context);
                parameters[SignatureProperty].RetrieveValue(context.Activity, ExecutePowerShellActivity.SignatureProperty, context);
                parameters[Var1Property].RetrieveValue(context.Activity, ExecutePowerShellActivity.Var1Property, context);
                parameters[Var2Property].RetrieveValue(context.Activity, ExecutePowerShellActivity.Var2Property, context);
                parameters[Var3Property].RetrieveValue(context.Activity, ExecutePowerShellActivity.Var3Property, context);
                parameters[Var4Property].RetrieveValue(context.Activity, ExecutePowerShellActivity.Var4Property, context);
                parameters[Var5Property].RetrieveValue(context.Activity, ExecutePowerShellActivity.Var5Property, context);
                parameters[SecureProperty].RetrieveValue(context.Activity, ExecutePowerShellActivity.SecureProperty, context);
                parameters[SecureStoreAppIdProperty].RetrieveValue(context.Activity, ExecutePowerShellActivity.SecureStoreAppIdProperty, context);
                parameters[Var1OutputProperty].RetrieveValue(context.Activity, ExecutePowerShellActivity.Var1OutProperty, context);
                parameters[Var2OutputProperty].RetrieveValue(context.Activity, ExecutePowerShellActivity.Var2OutProperty, context);
                parameters[Var3OutputProperty].RetrieveValue(context.Activity, ExecutePowerShellActivity.Var3OutProperty, context);
                parameters[Var4OutputProperty].RetrieveValue(context.Activity, ExecutePowerShellActivity.Var4OutProperty, context);
                parameters[Var5OutputProperty].RetrieveValue(context.Activity, ExecutePowerShellActivity.Var5OutProperty, context);
                //Logger.LogTraceMessage(LoggingConstants.TraceMessage.End, LoggingAreaCategory);

                return config;
            }
            catch (System.SystemException ex)
            {
                //Logger.LogToOperations(ex, (int)EventId.ActionError, EventSeverity.Error, LoggingAreaCategory);
                throw;
            }
        }

        public override ActionSummary BuildSummary(ActivityContext context)
        {
            try
            {
                // Construct an ActionSummary class to display details about this action.
                //Logger.LogTraceMessage(LoggingConstants.TraceMessage.Begin, LoggingAreaCategory);

                Dictionary<string, ActivityParameterHelper> parameters = context.Configuration.GetParameterHelpers();

                string displayMessage = string.Format("Run the following PowerShell script:{0}", parameters[ScriptProperty].Value);
                //Logger.LogTraceMessage(LoggingConstants.TraceMessage.End, LoggingAreaCategory);

                return new ActionSummary(displayMessage);
            }
            catch (System.SystemException ex)
            {
                //Logger.LogToOperations(ex, (int)EventId.ActionError, EventSeverity.Error, LoggingAreaCategory);
                throw;
            }

        }

        private bool IsSigningRequired
        {
            get
            {
                if (!SPFarm.Local.Properties.ContainsKey(Constants.ExecutePowerShellActivitySigningRequired))
                {
                    //Logger.LogToOperations("Defaulting to signing is required Farm property missing", (int)EventId.TraceMessage, EventSeverity.Warning, LoggingAreaCategory);
                    return true;
                }
                else
                {
                    return (bool)SPFarm.Local.Properties[Constants.ExecutePowerShellActivitySigningRequired];
                }

            }
        }

    }
}